<template>
    <div class="integral_exchange">
        <x-header v-show="!isWeChar" class="myHeader">
            <div slot="default" class="common__header--title">{{pageTitle}}</div>
            <div @click="goBack" slot="overwrite-left" class="common__header--img">
                <img slot="icon" src="~assets/x3/ico/goback1.png" class="go-back">
            </div>
        </x-header>
        <div class="background">
            <div class="balance">
                <div class="title">
                    <img src="~assets/x3/ico/dog_head.png" width="20">
                    <span>当前可用宝豆：</span>
                </div>
                <div class="number">{{integral.integralData.myscore.effctiveScore | filter_moeny}}</div>
            </div>

            <div class="selectBank">
                <div class="selectBank_title">到账银行卡：</div>
            </div>
            <div class="bankName" @click="showBnaks" v-html="incomeBank.label"></div>

            <div class="exchange_beans">
                <div class="left">
                    <x-input type="number" placeholder="请输入宝豆" v-model="inputBeans" @on-change="changeBeans">
                        <span slot="label">宝&nbsp;&nbsp;豆&nbsp;：&nbsp;</span>
                    </x-input>
                </div>
            </div>
            <!-- <div class="middle">⇋</div> -->
            <div class="exchange_rmb">
                <span>人民币：&nbsp;</span>
                <span class="no">{{exchangeMoney}}</span>
            </div>
            <div class="exchange_rmb_symbol">RMB</div>

            <x-button class="btn" :class="{btn_plain_disabled : isDisabled,btn_plain_default : !isDisabled}" :disabled="isDisabled" plain @click.native="exChangeBeans">立即兑换</x-button>
            <div class="all_exchange">
                <div class="all_exchange-proportion">{{exchangeAmount}}宝豆 = 1元人民币</div>
                <div class="all_exchange-btn" @click="allExChange">全额兑换</div>
            </div>
            <div class="btn_list" @click="goCashList">查看宝豆兑换记录</div>
        </div>
        <!-- 银行卡列表 -->
        <actionsheet v-model="isShowBanks" :menus="myBanks" @on-click-menu="selectedBank" show-cancel></actionsheet>
    </div>
</template>

<script>
import { RequestUrl } from 'src/common/url';
import { RouteUrl, Mutations } from "src/common/const";
import { XHeader, Group, Cell, XInput, XButton, Actionsheet } from "vux";
import { mapState } from "vuex";
export default {
    components: { XHeader, Group, Cell, XInput, XButton, Actionsheet },
    computed: mapState(["user", "isWeChar", "integral", "saveInsure"]),
    data() {
        return {
            pageTitle: "兑换",
            exchangeAmount: 100,//宝豆兑换人民币一元的量
            inputBeans: "",//输入的宝豆量
            exchangeMoney: "0",//兑换的人民币
            isShowBanks: false,//是否显示银行卡列表
            isDisabled: true,//是否禁用按钮
            myBanks: [],//银行卡列表
            incomeBank: {},//到账银行卡
        }
    },
    filters: {
        //格式化数字
        filter_moeny(val) {
            // if (!isNaN(val)) {
            //     val = val.toFixed(2);//四舍五入保留2位
            // }
            val = val + "";
            if (val.length > 3) {
                val = val.replace(/\B(?=(?:\d{3})+\b)/g, ',');
            }
            return val;
        },
    },
    methods: {
        goBack() {
            this.$common.goBackUrl(this, RouteUrl.MY_INTEGRAL);//返回
        },
        goCashList() {
            this.$common.goUrl(this, RouteUrl.INTEGRAL_EXCHANGE_LIST);//兑换记录
        },
        //全额兑换
        allExChange() {
            this.inputBeans = this.integral.integralData.myscore.effctiveScore;
        },
        //校验输入宝豆额
        checkNo(val) {
            val = val + "";//转字符串
            var positive_int1 = new RegExp(/^[1-9]{1,8}$/);//正整数(1-9的数字)
            var positive_int2 = new RegExp(/^[1-9]\d{1,7}$/);//正整数(1-9开头,0-9任意1-8位)
            var positive_float1 = new RegExp(/^[1-9]\d{1,7}\.\d{1,2}$/);//正浮点数大于9
            var positive_float2 = new RegExp(/^[1-9]{1,8}\.\d{1,2}$/);//正浮点数1<=n<10
            // var positive_float3 = new RegExp(/^0\.[1-9]{1}\d{1}$/);//正浮点数0.[1-9]x
            // var positive_float4 = new RegExp(/^0\.\d{1}[1-9]{1}$/);//正浮点数0.x[1-9]
            //数字校验和全0校验
            if (!(positive_int1.test(val) || positive_int2.test(val)
                || positive_float1.test(val) || positive_float2.test(val))
                || (val.length > 0 && parseInt(val) < 1)) {
                // this.inputBeans = "";//置空输入框
                return false;
            }
            //最大可兑换量
            let balance = this.integral.integralData.myscore.effctiveScore;
            if (val > balance) {
                this.$common.showMsg(this, "不能超过宝豆余额", "red;", true);
                return false;
            }
            return true;//输入正确
        },
        //输入宝豆时自动计算人民币
        changeBeans(val) {
            if (!this.checkNo(val)) {
                this.isDisabled = true;//禁用兑换按钮
                this.exchangeMoney = "0";//人民币
                return;
            }
            this.isDisabled = false;//兑换按钮可用
            this.exchangeMoney = (this.inputBeans / this.exchangeAmount).toFixed(2);
            this.exchangeMoney = (this.exchangeMoney + "").replace(/\B(?=(?:\d{3})+\b)/g, ',');
        },
        //提交兑换
        exChangeBeans() {
            this.changeBeans(this.inputBeans);//校验
            if (this.inputBeans < 100) {
                this.$common.showMsg(this, "宝豆兑换最低100个", "red;", true);
                return;
            }
            let _this = this;
            if (_this.$common.isEmpty(_this.incomeBank.userName)
                || _this.$common.isEmpty(_this.incomeBank.idNumber)
                || _this.incomeBank.fullName.indexOf("没有记录的卡号") >= 0
                || _this.$common.isEmpty(_this.incomeBank.province)
                || _this.$common.isEmpty(_this.incomeBank.city)) {
                _this.$vux.confirm.show({
                    content: _this.$common.alertMsg("银行卡信息不完善，请重新绑定！", "red;"), //显示内容
                    showInput: false, //是否显示input
                    confirmText: "确认",
                    cancelText: "取消",
                    onCancel() { ; },
                    onConfirm() {
                        _this.$common.goUrl(_this, RouteUrl.MGT_BANKS);
                    }
                });
                return;
            }
            let data = {
                TYPE: 'FORM',
                userCode: _this.user.userDto.userCode,//用户编码
                score: _this.inputBeans,//积分
                branchCode: _this.saveInsure.hotArea.branchCode,//机构编码
                bankNumber: _this.incomeBank.number,//银行卡号
                bankId: _this.incomeBank.id,//银行卡ID
            }
            //根据ID缓存已查看的数据
            _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, true);//loading
            _this.$http.post(RequestUrl.INTEGRAL_CASH, data).then(function (res) {
                _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, false);//loading
                if (res.state != 0) {
                    _this.$common.showMsg(_this, res.result, "red;", true);
                    return;
                }
                let showTime = setTimeout(() => {
                    _this.$vux.alert.hide();
                    _this.$common.goUrl(_this, RouteUrl.MY_INTEGRAL);
                }, 3000);
                //提示信息
                _this.$vux.alert.show({
                    content: _this.$common.alertMsg("兑换成功", "green;"),
                    onHide() {
                        clearTimeout(showTime);
                        _this.$common.goUrl(_this, RouteUrl.MY_INTEGRAL);
                    }
                });
            });
        },
        subForm(operation, done) {
            let queryData = {
                _this: this,
                userCode: this.user.userDto.userCode,
                operation: operation,
                selectCurType: this.selectCurType,
                done: done
            };
            this.isQuery = true;//可查询
            this.$common.storeCommit(this, Mutations.INTEGRAL_IN_OR_OUT_LIST, queryData);
        },
        //选择银行卡
        selectedBank(key, item) {//key值
            if (key == "cancel") {
                // console.log("选择了取消项");
            } else {
                this.incomeBank = item;
                // console.log("当前选中银行卡：" + this.incomeBank.fullName);
            }
        },
        //打开银行卡列表
        showBnaks() {
            this.isShowBanks = true;
        },
        initBanks() {
            this.myBanks = [];//先置空
            this.myBanks.push(this.getBankTitle());//添加列表标题
            let list = this.user.userDto.banks;
            for (let i = 0; i < list.length; i++) {
                let obj = this.getBank(list[i]);//选项列表对象
                if (list[i].isDefault == 1) {
                    this.incomeBank = obj;//默认银行卡
                }
                this.myBanks.push(obj);//追加每张银行卡
            }
        },
        getBank(bank) {
            let typeName = "";
            if (this.$common.isNotEmpty(bank.typeName)) {
                typeName = " · " + bank.typeName;
            }
            return {
                label: "<div style='font-size:15px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;'>"
                    + bank.fullName + typeName + "( <span style='color: #C8161D;'>"
                    + bank.number.substring(bank.number.length - 4, bank.number.length) + "</span> )</div>",
                id: bank.id,//记录id
                number: bank.number,//银行卡号
                mobile: bank.mobile,// 卡人姓名
                userName: bank.userName,// 银行预留手机号
                idNumber: bank.idNumber,// 持卡人身份证号
                fullName: bank.fullName,// 银行全称
                typeName: bank.typeName,// 银行卡卡种名称
                branchName: bank.branchName,// 开户支行名称
                province: bank.province,// 银行所属省份
                city: bank.city,// 银行所属市
                area: bank.area,// 银行所属区
                detailedAddress: bank.detailedAddress,// 开户行详细地址
                isDefault: 1// 是否默认银行卡,0=非默认,1=默认
            };
        },
        getBankTitle() {
            return {
                label: "<div style='color:#000;font-size:16px;padding: 0px 5px;'>请选择到账银行卡</div>"
                    + "<div style='color:#ccc;font-size:12px;padding: 0px 5px;'>请留意各银行卡尾号</div>",
                type: 'disabled'
            };
        },
    },
    created() {
        if (!this.user.isLogin) {
            this.$common.goUrl(this, RouteUrl.LOGIN);//需要登录
            return;
        }
        let _this = this;
        //没有银行卡不可提现
        if (_this.$common.isEmpty(_this.user.userDto.banks) || _this.user.userDto.banks.length < 1) {
            this.$common.goUrl(this, RouteUrl.MGT_BANKS);//需要绑定银行卡
            return;
        }
    },
    beforeRouteEnter(to, from, next) {
        sessionStorage["MGT_ID_NUMBER_FORM_URL"] = from.path;//刷新时的地址
        next();
    },
    beforeMount() {
        if (sessionStorage["MGT_ID_NUMBER_FORM_URL"] == "/") {//刷新时返回列表页
            this.$common.goUrl(this, RouteUrl.MY_INTEGRAL);
            return;
        }
    },
    mounted() {
        document.title = this.pageTitle;
        this.$init.subPageInit(this);
        this.initBanks();//初始化银行卡
    }
}
</script>

<style lang="scss" scoped>
.integral_exchange {
  width: 100%;
  height: 100vh;
  .myHeader {
    z-index: 2;
  }
  .background {
    height: 100%;
    padding-top: 30px;
    color: gray;
    background-color: white;
    //可用余额
    .balance {
      width: 80%;
      height: 150px;
      color: white;
      background-image: url("~assets/x3/ico/exchange_beans.jpg");
      background-size: 100% 100%;
      -moz-background-size: 100% 100%;
      -webkit-background-size: 100% 100%;

      margin: 0px auto;
      padding: 0px 20px;
      font-size: 18px;
      border-radius: 10px;
      box-shadow: 0px 10px 20px -10px #C8161D;

      .title {
        height: 40px;
        line-height: 40px;
        padding-top: 9px;
        color: #c9defe;
        border-bottom: 1px solid #ccc;

        img {
          display: block;
          float: left;
          margin-top: 10px;
          margin-right: 10px;
        }
      }
      .number {
        height: 100px;
        line-height: 100px;
        font-size: 30px;
        font-weight: bolder;
        text-align: center;
      }
    }
    //兑换金额
    .exchange_beans {
      width: 90%;
      margin: 10px auto 0px auto;
      height: 40px;
      line-height: 40px;
      .left {
        color: #C8161D !important;
        font-weight: bolder !important;
        font-size: 16px !important;
        // border-bottom: 1px solid #eee;
        div {
          span {
            color: dimgray;
            font-size: 18px;
            font-weight: normal;
            margin-right: 8px !important;
          }
        }
        .weui-cell {
          padding: 0px;
        }
      }
    }
    // .middle {
    //   width: 90%;
    //   margin: 0px auto;
    //   height: 40px;
    //   line-height: 40px;
    //   font-size: 24px;
    // }
    .exchange_rmb {
      width: 70%;
      float: left;
      margin: 0px 0px 0px 5%;
      height: 40px;
      line-height: 40px;
      color: dimgray;
      font-size: 18px;
      font-weight: normal;
      //   border-bottom: 1px solid #eee;
      .no {
        color: #C8161D;
        font-weight: bolder !important;
      }
    }
    .exchange_rmb_symbol {
      float: right;
      width: 18%;
      margin: 0px 7% 0px 0px;
      height: 40px;
      line-height: 40px;
      color: gray;
      font-size: 14px;
      text-align: right;
      font-weight: normal;
    }
    //全额兑换按钮
    .all_exchange {
      clear: both;
      width: 90%;
      height: 30px;
      line-height: 30px;
      margin: 10px auto;
      .all_exchange-proportion {
        float: left;
        width: 60%;
      }
      .all_exchange-btn {
        float: right;
        width: 25%;
        text-align: right;
        padding-right: 5%;
      }
    }
    //兑换按钮
    .btn {
      width: 90%;
      height: 45px;
      line-height: 45px;
      text-align: center;
      margin-top: 10px;
      //   border: 2px solid #C8161D;
      //   color: #C8161D;
      font-weight: bolder;
    }
    .btn_plain_disabled {
      color: rgba(0, 0, 0, 0.2);
      border-color: rgba(0, 0, 0, 0.2);
      border: 2px solid rgba(0, 0, 0, 0.2);
    }
    .btn_plain_default {
      color: #C8161D;
      border: 2px solid #C8161D;
    }
    //兑换记录按钮
    .btn_list {
      width: 89%;
      height: 50px;
      line-height: 50px;
      margin: 20px auto 0px auto;
      text-align: center;
      border: 1px solid #eee;
      border-radius: 5px;
      font-weight: bolder;
      color: #ccc;
    }
    //银行卡
    .selectBank {
      width: 90%;
      margin: 20px auto 0px auto;
      height: 40px;
      line-height: 40px;
      font-size: 15px;

      .selectBank_title {
        float: left;
        width: 35%;
      }
    }
    .bankName {
      width: 90%;
      margin: 0px auto;
      height: 30px;
      line-height: 30px;
      font-size: 15px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #C8161D;
    }
    .bankds_default {
      color: red;
    }
  }
}
</style>

